'''
Description: description
Author: 
LastEditors: M
'''
from threading import Thread
import psutil
import time
import queue

from compoments.config import COOL_TIME
"""
启动15s后启动第一个进程
两个进程启动之间间隔60s

使用多线程
"""
class SYS_STATISTIC():
    cpu_rate=0
    mem_rate=0
    STOP_tick= False
    READY = False
    def _set_cpu_rate(self,cr):
        self.cpu_rate = cr
    def _set_mem_rate(self,mr):
        self.mem_rate = mr
    def stop_statistic(self):
        self.STOP_tick=True
        if self._t_statistic is not None:
            self._t_statistic.join()
    def get_now_cpu_and_mem_rate(self):
        return self.cpu_rate,self.mem_rate
    def _set_ready(self):
        self.READY =True

    _call_once = True 
    def _statistic_thread(self):
        TICK_STATIC = 60  
        TICK_INTERVAL = 1  
        tick_interval_cool_period=COOL_TIME/TICK_STATIC

        tick_quene_cpu =queue.Queue(maxsize=TICK_STATIC+1)
        tick_quene_mem =queue.Queue(maxsize=TICK_STATIC+1)

        sum_mem = 0
        sum_cpu = 0
        for i in range(TICK_STATIC):
            time.sleep(tick_interval_cool_period)
            mem_rate = psutil.virtual_memory().percent
            cpu_rate = psutil.cpu_percent(None)
            sum_mem+=mem_rate
            sum_cpu+=cpu_rate
            tick_quene_cpu.put_nowait(cpu_rate)
            tick_quene_mem.put_nowait(mem_rate)
        
        self._set_ready()
        self._set_cpu_rate(sum_cpu/TICK_STATIC)
        self._set_mem_rate(sum_mem/TICK_STATIC)
        while True:
            if self.STOP_tick:
                return 
            time.sleep(TICK_INTERVAL)        
            last_cpu_rate = tick_quene_cpu.get_nowait()
            last_mem_rate = tick_quene_mem.get_nowait()
            mem_rate = psutil.virtual_memory().percent
            cpu_rate = psutil.cpu_percent(None)
            tick_quene_cpu.put_nowait(cpu_rate)
            tick_quene_mem.put_nowait(mem_rate)
            sum_mem+=mem_rate-last_mem_rate
            sum_cpu+=cpu_rate-last_cpu_rate
            self._set_cpu_rate(sum_cpu/TICK_STATIC)
            self._set_mem_rate(sum_mem/TICK_STATIC)
    
    _t_statistic = None
    def start_statistic(self):
        """
        只应该被启动一次
        启动一个子线程 启动成功返回 线程 失败或已启动返回None
        @return: (t:thread,msg)
        """
        msg = "success"
        if not self._call_once:
            msg = "it have been called"
            return None,msg 
        self._call_once = False 
        
        t = Thread(target=self._statistic_thread)
        t.start()
        self._t_statistic = t
        return t,msg
    def now_remain(self):
        """
        计算当前剩余的
        @return cpu_remain,mem_remain
        """
        return 100-self.cpu_rate,100-self.mem_rate
    def delta_to(self,tick_cpu_r,tick_mem_r):
        """
        计算当前时刻与给定 值的差值
        in_cpu,in_mem
        @return now-tick_cpu_r,now-tick_mem_r
        """
        return self.cpu_rate-tick_cpu_r,self.mem_rate-tick_mem_r
